package com.classroompie.classroompieserver.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.classroompie.classroompiecommon.result.Result;
import com.classroompie.classroompiecommon.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jiahao
 * @since 2024/6/26 周三
 */
@RequestMapping("/gv")
@RestController
@CrossOrigin("*")
public class CaptchaController {

    // 模拟缓存
    Map<String,String> cache = new HashMap<>();

    /**
     * 给前端返回一个base64格式的图片，前端需要转换为图片
     * @return
     */
    @GetMapping("/identifyImageBase64")
    public String identifyImageBase64() {
        // 定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 90, 4, 100);
        // 验证码值
        String code = lineCaptcha.getCode();
        String uuid = UUIDUtil.UUID();
        // 将验证码值存入缓存
        cache.put(uuid, code);
        System.out.println("验证码值：" + code);
        // 验证码以base64的格式返回到客户端
        return lineCaptcha.getImageBase64Data();
    }

    @GetMapping("/verifyCode")
    public Result verifyCode(@RequestParam String code, String uuid) {
        // 从缓存中取出验证码
        String cacheCode = cache.get(uuid);
        if (cacheCode == null) {
            cache.remove(uuid);
            return Result.error("验证码已过期");
        }
        // 判断验证码是否正确
        if (!cacheCode.equals(code)) {
            cache.remove(uuid);
            return Result.error("验证码错误");
        }
        cache.remove(uuid);
        return Result.success();
    }


}